//app.js
const api = require('./api/api');
App({
  onLaunch: function () {   
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
         env: 'cloud1-5gcbfdljbabe0356',
        traceUser: true,
      })
    }
    const openid = wx.getStorageSync('openid')
    console.log(openid)
    if(openid){
      this.getUser(openid)
      this.globalData.openid = openid
    }
    else{
      console.log(2)
      this.getOpenid()
      
    }
  },
  globalData:{
    userInfo:null,
    isLogin:false,
    openid:'',
    id:''
  },
  getUser(openid){
    wx.request({
      url: api.getUserInfo.url,
      method:api.getUserInfo.method,
      data:{
        openid:openid
      },
      success:res=>{
       console.log(res)
       if(res.data.code==200){
          this.globalData.isLogin = true
          this.globalData.userInfo = res.data.data[0]
          this.globalData.id = res.data.data[0].id
       }
      }
    })
  },
  getOpenid(){
    wx.cloud.callFunction({
      name:"login",
      success:res=>{
        console.log(res)
        const openid = res.result.openid
        this.globalData.openid = openid
        wx.setStorageSync('openid', openid)
        this.getUser(openid)
      }
    })
  }
})
